package com.imooc.service.impl;

import com.imooc.bo.SearchReportJobBO;
import com.imooc.enums.DealStatus;
import com.imooc.enums.JobStatus;
import com.imooc.mapper.JobMapper;
import com.imooc.mo.ReportMO;
import com.imooc.pojo.Job;
import com.imooc.repository.ReportJobRepository;
import com.imooc.service.ReportService;
import com.imooc.utils.PagedGridResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author liansen
 * @create 05-29-2:26
 */
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportJobRepository reportJobRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void saveReportJob(ReportMO reportMO) {
        reportMO.setDealStatus(DealStatus.WAITING.type);
        reportMO.setCreatedTime(LocalDateTime.now());
        reportMO.setUpdatedTime(LocalDateTime.now());
        reportJobRepository.save(reportMO);
    }

    @Override
    public boolean isExistReportJob(String reportUserId, String jobId) {
        ReportMO reportMO = reportJobRepository.findByReportUserIdAndJobId(reportUserId, jobId);
        return reportMO != null;
    }

    @Override
    public PagedGridResult pagedReportRecordList(SearchReportJobBO searchReportJobBO, Integer page, Integer limit) {

        String jobName = searchReportJobBO.getJobName();
        String companyName = searchReportJobBO.getCompanyName();
        Integer dealStatus = searchReportJobBO.getDealStatus();
        String reportUserName = searchReportJobBO.getReportUserName();
        LocalDateTime beginDateTime = searchReportJobBO.getBeginDateTime();
        LocalDateTime endDateTime = searchReportJobBO.getEndDateTime();

        //创建查询对象
        Query query = new Query();

        //创建条件对象
        Criteria criteria = new Criteria();

        //设置查询条件
        if(StringUtils.isNotBlank(jobName)){
            query = addLikeByValue(query, "job_name", jobName);
        }

        if(StringUtils.isNotBlank(companyName)){
            query = addLikeByValue(query, "company_name", companyName);
        }

        if(StringUtils.isNotBlank(reportUserName)){
            query = addLikeByValue(query, "report_user_name", reportUserName);
        }

        if(dealStatus != null){
            query.addCriteria(Criteria.where("deal_status").is(dealStatus));
        }

        if(beginDateTime != null){
            query.addCriteria(Criteria.where("created_time").gte(beginDateTime));
        }

        if(endDateTime != null){
            query.addCriteria(Criteria.where("created_time").lte(endDateTime));
        }

        //查询记录总数，必须在分页前查询，不然总数统计不对
        long counts = mongoTemplate.count(query, ReportMO.class);

        //设置分页
        Pageable pageable = PageRequest.of(page, limit, Sort.Direction.DESC, "created_time");

        query.with(pageable);

        List<ReportMO> list = mongoTemplate.find(query, ReportMO.class);

        //封装分页
        PagedGridResult result = new PagedGridResult();
        result.setRows(list);
        result.setRecords(counts);
        result.setPage(page);
        result.setLimit(limit);
        return result;
    }

    private Query addLikeByValue(Query query, String key, String value) {
        Pattern pattern = Pattern.compile("^.*" + value + ".*$");
        query.addCriteria(Criteria.where(key).regex(pattern));
        return query;
    }

    @Override
    public void updateReportRecordStatus(String reportId, DealStatus status) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(reportId));

        Update update = new Update();
        update.set("deal_status", status.type);
        update.set("updated_time", LocalDateTime.now());

        if(status == DealStatus.DONE){
            ReportMO reportMO = reportJobRepository.findById(reportId).get();
            String jobId = reportMO.getJobId();
            Job job = new Job();
            job.setId(jobId);
            job.setStatus(JobStatus.DELETE.type);
            job.setViolateReason(reportMO.getReportReason());
            job.setUpdatedTime(LocalDateTime.now());
            jobMapper.updateById(job);
            Job jobTemp = jobMapper.selectById(jobId);
            redisTemplate.delete("redis_job_detail" + ":" + jobTemp.getCompanyId() + ":" + jobTemp.getHrId() + ":" + jobId);
        }

        mongoTemplate.updateFirst(query, update, ReportMO.class);
    }

}
